
import com.alogic.json.JsonFactory;
import com.alogic.xscript.ExecuteWatcher;
import com.alogic.xscript.Logiclet;
import com.alogic.xscript.LogicletContext;
import com.alogic.xscript.Script;
import com.alogic.xscript.doc.XsObject;
import com.alogic.xscript.doc.json.JsonObject;
import com.anysoft.util.*;
import com.anysoft.util.resource.ResourceFactory;
import com.logicbus.backend.daemon.DaemonServer;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;

import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

public class Main {
    /**
     * a logger of slf4j
     */
    protected static final Logger LOG = LoggerFactory.getLogger(Main.class);

    public static Logiclet create(String src, Properties p){
        Logiclet script = null;

        if (StringUtils.isNotBlank(src)){
            ResourceFactory resourceFactory = Settings.getResourceFactory();
            InputStream in = null;
            try {
                in = resourceFactory.load(src,null);
                Document doc = XmlTools.loadFromInputStream(in);

                if (doc != null){
                    script = new Script.Container("script", Script.Library.get());
                    script.registerModule("script", Script.class);
                    script.configure(doc.getDocumentElement(), p);
                }
            }catch (Exception ex){
                LOG.error("The config file is not a valid file,url = " + src,ex);
            }finally{
                IOTools.close(in);
            }
        }

        return script;
    }

    public static void runAsJson(String src, Properties p) {
        try {
            Logiclet script = create(src, p);
            if (script == null) {
                System.out.println("Fail to compile the script");
                return;
            }
            long start = System.currentTimeMillis();
            Map<String, Object> root = new HashMap<String, Object>();
            XsObject doc = new JsonObject("root", root);
            LogicletContext ctx = new LogicletContext(p);
            script.execute(doc, doc, ctx, new ExecuteWatcher.Quiet());

            System.out.println("Script:" + src);
            System.out.println("Duration:" + (System.currentTimeMillis() - start) + "ms");

            JsonFactory jsonFactory = Settings.getToolkit(JsonFactory.class);
            System.out.println("#########################################################");
            System.out.println(jsonFactory.toJsonString(root));
            System.out.println("#########################################################");
        } catch (Exception ex) {
            LOG.error(ExceptionUtils.getStackTrace(ex));
        }
    }

    public static void loadDaemon(Settings settings){
        //加载daemon事件服务器
        String daemonConfig = settings.GetValue("daemon.master", "");
        String daemonConfigSecondary = settings.GetValue("daemon.secondary","");
        if (StringUtils.isNotEmpty(daemonConfig)){
            LOG.info("Load and start daemon event servers..");
            LOG.info("Url = " + daemonConfig);
            try {
                DaemonServer daemonServer = DaemonServer.loadFrom(daemonConfig, daemonConfigSecondary, settings);
                if (daemonServer != null){
                    daemonServer.start();
                    settings.registerObject("daemon", daemonServer);
                }
            }catch (Exception ex){
                LOG.error("Can not load and start daemon event servets");
            }
        }
    }
    public static void main(String[] args) {
        Settings settings = Settings.get();
        settings.addSettings(new CommandLine(args));
        settings.addSettings("java:///settings.xml#Main",null, Settings.getResourceFactory());
        loadDaemon(settings);
        runAsJson("java:///main.xml", settings);
    }
}
